package br.ufpe.cin.mac.util;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.cert.CertificateException;
import java.security.spec.RSAKeyGenParameterSpec;

public class CryptUtil {
	private static final int RSAKEYSIZE = 1024;
	/**
	 * Gera um par de chaves e as guarda em formato serializado em arquivos.
	 * @param fPub O arquivo que ira conter a chave publica.
	 * @param fPvk O arquivo que ira conter a chave privada.
	 * @throws IOException Problemas de acesso/gravacao do arquivo.
	 * @throws NoSuchAlgorithmException RSA nao disponivel nesta versao do JDK.
	 * @throws InvalidAlgorithmParameterException Nao deve ocorrer.
	 * @throws CertificateException Nao deve ocorrer.
	 * @throws KeyStoreException Nao deve ocorrer.
	 */
	public void geraParChaves(File fPub, File fPvk) throws IOException,
			NoSuchAlgorithmException, InvalidAlgorithmParameterException,
			CertificateException, KeyStoreException {

		KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
		kpg.initialize(new RSAKeyGenParameterSpec(RSAKEYSIZE,
				RSAKeyGenParameterSpec.F4));
		KeyPair kpr = kpg.generateKeyPair();
		PrivateKey priv = kpr.getPrivate();
		PublicKey pub = kpr.getPublic();

		// -- Gravando a chave p�blica em formato serializado
		ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(
				fPub));
		oos.writeObject(pub);
		oos.close();

		// -- Gravando a chave privada em formato serializado
		// -- N�o � a melhor forma (deveria ser guardada em um keystore, e
		// protegida por senha),
		// -- mas isto � s� um exemplo
		oos = new ObjectOutputStream(new FileOutputStream(fPvk));
		oos.writeObject(priv);
		oos.close();

	}
	public static void main (String args[]){
		CryptUtil util = new CryptUtil();
		try {
			util.geraParChaves(new File("chave.publica"), new File("chave.privada"));
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvalidAlgorithmParameterException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (CertificateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (KeyStoreException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}
